package com.kyzh.core.pager.weal.vip

import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.os.Bundle
import android.text.Html
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.view.setPadding
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.google.android.material.tabs.TabLayout
import com.gushenge.atools.util.setHeight
import com.gushenge.atools.util.setWidth
import com.gushenge.core.beans.VipBean
import com.gushenge.core.impls.VipImpl
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.gushenge.core.base.activity.BaseActivity
import com.kyzh.core.databinding.ItemVipBinding
import com.kyzh.core.databinding.TablayoutVipTextBinding
import com.kyzh.core.dialog.showVipDialog
import com.kyzh.core.utils.*
import kotlinx.android.synthetic.main.activity_vip.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.textColor
import java.util.*

class VipActivity : BaseActivity(){
    companion object{
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, VipActivity::class.java)
            context.startActivity(starter)
        }
    }
    private var datas :VipBean?= null
    private var myDengJi : Int = 0
    private var adapter:BaseQuickAdapter<VipBean.Gongneng, BaseDataBindingHolder<ItemVipBinding>>? =null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_vip)
        titleView.setBg(R.drawable.bg_standard)
        initData()
    }
    //加载数据
    fun initData(){
        VipImpl.getVip{
            datas =  this
            val encodeToString = Base64.decode(datas?.jieshao?.toByteArray(),Base64.DEFAULT)
            val string = String(encodeToString)
            val replace1 = string.replace("<p>", "<br>")
            val replace = replace1.replace("</p>", "</br>")
            tvTips.text = Html.fromHtml( replace)
            tvButton.text = datas?.pay_submit
            initTab()
            initGongNeng()
            initTop()
        }
    }


    fun jumpCentre(){
        VipCentreActivity.start(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == RESULT_OK){
          if(requestCode ==1000){
              initData()
          }
        }
    }


    /**
     * 顶部
     */
    fun initTop(){
        datas?.top?.apply {
            if(vip==0){
                groupTop1.setVisibility(true)
                groupTop2.setVisibility(false)
                viewBgNoVip.loadImage(bgimg)
            }else{
                groupTop1.setVisibility(false)
                groupTop2.setVisibility(true)
//                viewBgVip.loadImage(bgimg)
                iconHead.loadImage(head)
                imgHuangGuan.loadImage(icon)
                if(head_frame.isNullOrBlank()){
                    iconHead.setWidth(dip(73))
                    iconHead.setHeight(dip(73))
                }else{
                    iconHead.setWidth(dip(73))
                    iconHead.setHeight(dip(73))
                }
                ivBg.loadImage(head_frame)
                tvName.text = name
                progress.progress = exp*100/last_exp
                if(style_img.isNullOrEmpty()||style_exp.isNullOrEmpty()){
                    imgUp.setVisibility(false)
                    tvUp.setVisibility(false)
                }else{
                    imgUp.loadImage(style_img)
                    if(style_exp.contains("-")){
                        tvUp.textColor = resources.getColor(R.color.exp_red)
                    }else{
                        tvUp.textColor = resources.getColor(R.color.exp_green)
                    }
                    tvUp.text = style_exp
                }
                tvExp.text = "当前VIP值：${exp}，距离下一级剩余:${last_exp-exp}"
                tvTime. text =end_time
                if(is_pay == 0){
                    tvOpen .text = "开通"
                }else{
                    tvOpen .text = "续费"
                }
                tvOpen.setOnClickListener {
                    OpenVipActivity.start(this@VipActivity)
                }
            }
            LiveEventBus.get<String?>("frame_img").observe(this@VipActivity){
                if(it.isNullOrBlank()){
                    iconHead.setWidth(dip(73))
                    iconHead.setHeight(dip(73))
                    ivBg.loadImage(it)
                }else{
                    iconHead.setWidth(dip(50))
                    iconHead.setHeight(dip(50))
                    ivBg.loadImage(it)
                }
            }
            LiveEventBus.get<String?>("icon_img").observe(this@VipActivity){
//                if(it.isNullOrBlank()){
//                    imgHuangGuan.setVisibility(false)
//                }else{
//                    imgHuangGuan.setVisibility(true)
                    imgHuangGuan.loadImage(it)
//                }
            }
            viewButton.setOnClickListener {
                if (startLogin()) {
                    OpenVipActivity.start(this@VipActivity)
                }
            }
            tvButton.setOnClickListener {
                if (startLogin()) {
                    OpenVipActivity.start(this@VipActivity)
                }
            }
            tvOpen.setOnClickListener {
                if (startLogin()) {
                    OpenVipActivity.start(this@VipActivity)
                }
            }

        }
        // 开通会员

    }
    // 功能区域
    fun  initGongNeng(){
        rev.layoutManager = GridLayoutManager(this,3)
        adapter = object :
            BaseQuickAdapter<VipBean.Gongneng, BaseDataBindingHolder<ItemVipBinding>>(
                R.layout.item_vip,
                datas?.gongneng
            ) {
            override fun convert(
                holder: BaseDataBindingHolder<ItemVipBinding>,
                item: VipBean.Gongneng
            ) {
                holder.dataBinding?.data = item
                val acImage = holder.getView<AppCompatImageView>(R.id.acImage)
                val group = holder.getView<TextView>(R.id.tvTips)
                val tvTitle = holder.getView<TextView>(R.id.tvTitle)

                if (myDengJi < item.tiaojian) {
                    acImage.loadImage(item.icon_no)
                    group.setVisibility(true)
                    tvTitle.setTextColor(resources.getColor(R.color.font_99))
                } else {
                    group.setVisibility(false)
                    acImage.loadImage(item.icon)
                    tvTitle.setTextColor(resources.getColor(R.color.font_33))
                }

            }

        }
        rev.adapter =adapter
        (adapter as BaseQuickAdapter<VipBean.Gongneng, BaseDataBindingHolder<ItemVipBinding>>).setOnItemClickListener { adapter, view, position ->
            VipImpl.getQuanYi(datas!!.gongneng[position].type){
                this?.let {
                    this@VipActivity.showVipDialog(it){
                        //跳转到福利中心
                        jumpCentre()
                    }
                }

            }
        }
    }
    //标签页
    fun initTab(){
        datas?.dengji?.forEachIndexed { index, dengji ->
            if(dengji.status == "1"){
                myDengJi = dengji.tiaojian
            }
            val tab = table.newTab().apply {
                val inflate = DataBindingUtil.inflate<TablayoutVipTextBinding>(
                    LayoutInflater.from(this@VipActivity),
                    R.layout.tablayout_vip_text,
                    null,
                    false
                )
                setTag(dengji.tiaojian)
                val findViewById = inflate.root.findViewById<TextView>(R.id.tv)
                findViewById.text = dengji.title
                customView = inflate.root
                customView?.setPadding(0)
            }

            table.addTab(tab)
//            加分割线
//            val tabAt = table.getChildAt(0) as LinearLayout
//            tabAt.showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE
//            tabAt.dividerDrawable = resources.getDrawable(R.drawable.vip_fengexian)
//            tabAt.dividerPadding = dip(10)
        }
        table.getTabAt(0)?.customView?.setPadding(0)
        table.tabRippleColor = ColorStateList.valueOf(resources.getColor(R.color.white1))

        table.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val findViewById = tab?.customView?.findViewById<TextView>(R.id.tv)
                findViewById?.setTextColor(resources.getColor(R.color.font_33))
                findViewById?.textSize = 14f
                if (tab != null) {
                    myDengJi = tab.tag as Int
                    adapter?.notifyDataSetChanged()
                }
                tab?.customView?.findViewById<View>(R.id.view)?.setVisibility(true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                val findViewById = tab?.customView?.findViewById<TextView>(R.id.tv)
                findViewById?.setTextColor(resources.getColor(R.color.font_99))
                findViewById?.textSize = 12f
                tab?.customView?.findViewById<View>(R.id.view)?.visibility = View.INVISIBLE
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                val findViewById = tab?.customView?.findViewById<TextView>(R.id.tv)
                findViewById?.setTextColor(resources.getColor(R.color.font_33))
                findViewById?.textSize = 14f
                if (tab != null) {
                    myDengJi = tab.tag as Int
                    adapter?.notifyDataSetChanged()
                }
                tab?.customView?.findViewById<View>(R.id.view)?.setVisibility(true)
            }

        })
        table.post {

            datas?.dengji?.forEachIndexed { index, dengji ->
                if(dengji.status =="1"){

                    val i = table.getTabAt(index)
                    val i1 = i?.tag as Int
                    if(i1 == dengji.tiaojian){
                        table.selectTab( i)
                    }
                }
            }
        }

    }

}